package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import jakarta.annotation.Resource;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: TrackReceiver
 * Package: com.atguigu.tingshu.album.receiver
 * Description:
 *
 * @Author:
 * @Create: 2025/8/2 - 14:59
 * @Version: v1.0
 */

@Component
public class TrackReceiver {

    @Resource
    private TrackInfoService trackInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateTrackStat(ConsumerRecord<String,String> record){
        String value = record.value();
        TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);
        String key = trackStatMqVo.getBusinessNo();
        //通过向redis里添加数据防止在短时间内消息被重复消费，做到幂等性
        Boolean isExist = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 1, TimeUnit.HOURS);
        if(isExist){
            try {
                trackInfoService.updateTrackStat(trackStatMqVo);
            } catch (Exception e) {
                stringRedisTemplate.delete(key);
                e.printStackTrace();
            }
        }
    }
}
